<?php
/**
 * 项目名： AligenieTeach
 * 包名：BindPhoneActivity
 * 创建时间：2019/7/4  11:53
 * 创建者博客： http://blog.csdn.net/xh870189248
 * 创建者GitHub： https://github.com/xuhongv
 * 创建者：徐宏 XuHongYss
 * 描述： 绑定手机号码
 */

namespace app\wechat\controller;


use app\common\encrypt\Aes;
use think\Validate;

class BindPhoneActivity extends BaseWeChat
{


    private $dataArry;
    private $userOauth;


    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub


        try {
            // 实例接口
            $this->userOauth = new \WeChat\Oauth($this->mWeiChatOptions);

        } catch (\Exception $e) {
            // 异常处理
            echo $e->getMessage();
        }

        $result = null;

        if (!$this->localUser)
            try {
                //
                $result = $this->userOauth->getOauthRedirect($this->mWeiChatOptions['weichatDomain'].'/wechat/user', 'ok', 'snsapi_userinfo');
            } catch (\Exception $e) {
                // 异常处理
                echo $e->getMessage();
            }

        $this->dataArry = ['isOauth' => 0,
            'url' => $result,
            'headimgurl' => '',
            'nickName' => '未知',
            'sex' => '未知',
        ];
    }


    /**
     *  登陆账户使用
     * @return mixed
     */
    public function register()
    {


        if (!$this->request->isPost())
            return $this->fetch();

        $postData = input('post.');


        //校验数据是否合法
        $rule = new Validate(['phone' => 'require']);
        //判断是否匹配规则
        if (!$rule->check($postData)) {
            //提示错误信息
            return $this->utlisResponse($rule->getError(), false);
        }

        if (isset($postData['code'])) {
            return $this->utlisResponse('短信已经成功发送到您到手机，注意查看！', true);
        }


    }

    public function index()
    {

        // return $this->fetch('');

        //var_dump($this->localUser);
        $getData = input('get.');
        if (!is_array($getData))
            return '';

        if (!$this->localUser) {
            //判断是微信授权成功后的回调
            if (isset($getData['state']) && isset($getData['code'])) {
                if ($getData['state'] == 'ok') {
                    //  1 获取本地操作用户的 accesstoken和openid以及unionid
                    $_GET['code'] = $getData['code'];
                    try {
                        $result = $this->userOauth->getOauthAccessToken();
                    } catch (Exception $e) {
                        // 异常处理
                        echo '授权失败' . $e->getMessage();
                        $this->dataArry['isOauth'] = false;
                        $this->dataArry['url'] = '';
                        return $this->fetch('', $this->dataArry);
                    }
                    //  2 获取本地操作用户的 头像和昵称
                    $userInfo = $this->userOauth->getUserInfo($result["access_token"], $result['openid']);

                    //判断是否已有记录在服务器,根据 openid 为依据
                    $user = model('User')->get(['openId' => $userInfo['openid']]);

                    //var_dump($user);

                    if (!$user) {
                        // echo '未注册'; 开始默认注册账号
                        $saveData = [
                            'openId' => $userInfo['openid'],
                            'unionId' => isset($userInfo['unionid']) ? $userInfo['unionid'] : '', //判断是否有unionId
                            'name' => $userInfo['nickname'],
                            'sex' => $userInfo['sex'],
                            'access_token' => $result['access_token'],
                            'refresh_token' => $result['refresh_token'],
                            'create_time' => time(),
                            'create_token_time' => time(),
                            'update_time' => time(),
                            'pic' => $userInfo['headimgurl'],
                        ];
                        try {
                            model('User')->save($saveData);
                        } catch (\Exception $exception) {
                            echo '注册异常' . $exception->getMessage();
                        }
                    }
                    //start creat token
                    $deadline = getWeChatUnionTokenDeadline(time());
                    $tokenEncrypt = [
                        'name' => $userInfo['openid'], //unionid
                        'deadline' => $deadline, //获取token有效期
                    ];
                    $token = Aes::opensslEncrypt(json_encode($tokenEncrypt, true), config('encryptKey.AES_WECHAT_UNIONID_TOKEN'));
                    //end creat token

                    $this->dataArry['headimgurl'] = $userInfo['headimgurl'];
                    $this->dataArry['nickName'] = $userInfo['nickname'];
                    $this->dataArry['isOauth'] = true;
                    $this->dataArry['token'] = $token;
                    $this->dataArry['url'] = '';
                    $this->dataArry['deadline'] = $deadline; //token有效期

                    //登录态 session
                    $this->LoginIn($this->dataArry);
                }
            }
            return $this->fetch('', $this->dataArry);
            //已经登录
        } else {
            //从本地session获取
            $userInfo = ($this->localUser);
            if (!isset($userInfo['deadline'])) {
                $this->LoginOut();
                return $this->redirect($this->mWeiChatOptions['weichatDomain'] . '/wechat/user');
            } else {
                //如果缓存的token时间超过本地的最大时间，表示已经失效，需要重新授权
                if (time() > $userInfo['deadline']) {
                    $this->LoginOut();
                    return $this->redirect($this->mWeiChatOptions['weichatDomain'] . '/wechat/user');
                }
            }
            return $this->fetch('', $userInfo);
        }


    }


    public function createOauthCode()
    {


        //用户存在？

        $post = input('post.');


        //确定此设备是否属于该用户以及该设备是否在线
        //start 解密，判断是否是aes加密后数据
        $token = Aes::opensslDecrypt($this->localUser['token'], config('encryptKey.AES_WECHAT_UNIONID_TOKEN'));
        $token = json_decode($token);


        if ($token) {

            //判断有效期 是否处于有效期内？否则需要重新获取
            if (time() > $token->deadline) {
                return $this->utlisResponse('token失效！', false);
            }

            if (!isset($token->name)) {
                return $this->utlisResponse('非微信用户！', false);
            }

            //判断用户已经注册？
            try {
                $user = model('User')->get(['openId' => $token->name]);
            } catch (\Exception $exception) {
                return $this->utlisResponse('' . $exception->getMessage(), false);
            }

            if (!$user) {
                return $this->utlisResponse('该用户不存在！', false);
            }

            //1.获取当前用户下是否有code
            try {
                $codeModel = model('WcUserCode')->get(['user_id' => $user['id']]);
            } catch (\Exception $exception) {
                return $this->utlisResponse('' . $exception->getMessage(), false);
            }


            $yuan = '0123456789abcdefghigklmnopqrstyvwxyzQWERTYUIOPLKJHGFDSAZXCVBNM';
            $arr = str_split($yuan);
            $v_code = '';
            for ($i = 0; $i < 6; $i++) {
                $pos = mt_rand(0, count($arr));
                $v_code .= $arr[$pos];
            }

            $saveData = [
                'user_id' => $user['id'],
                'expire' => time() + config('oauth.wechatUserExpire'),
                'code' => $v_code,
                'active' => 0,
            ];

            if (!$codeModel) {
                try {
                    $codeModel = model('WcUserCode')->save($saveData);
                } catch (\Exception $exception) {
                    return $this->utlisResponse('' . $exception->getMessage(), false);
                }

                if ($codeModel) return $this->utlisResponse($codeModel['code'], true, ['code' =>$v_code]);
                else
                    return $this->utlisResponse('授权码未创建错误001' . json_encode($saveData), false);

            } else {
                try {
                    $codeModel = model('WcUserCode')->save($saveData, ['user_id' => $user['id']]);
                } catch (\Exception $exception) {
                    return $this->utlisResponse('' . $exception->getMessage(), false);
                }
                if ($codeModel) return $this->utlisResponse($codeModel['code'], true,['code' => $v_code]);
                else
                    return $this->utlisResponse('授权码未创建错误002', false);
            }


        } else {
            return $this->utlisResponse('非法用户！', false);
        }


    }

}